package com.daxt.controller.filemanager;

import java.time.LocalDateTime;
import java.util.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.daxt.base.common.util.RedisUtil;
import com.daxt.common.annotations.LoginAuth;
import com.daxt.common.annotations.LoginUser;
import com.daxt.common.annotations.OperLog;
import com.daxt.common.result.*;
import com.daxt.mapper.accept.BusinessInfoMapper;
import com.daxt.mapper.accept.FormDataMapper;
import com.daxt.mapper.sys.ArchivesClassMapper;
import com.daxt.mapper.sys.DicMapper;
import com.daxt.mapper.use.UseBorrowRecordMapper;
import com.daxt.model.constant.BaseConstants;
import com.daxt.model.dic.*;
import com.daxt.model.dto.BaseQueryDto;
import com.daxt.model.dto.Classifys;
import com.daxt.model.search.ArchivesSearch;
import com.daxt.model.service.accept.vo.FormData;
import com.daxt.model.service.archives.vo.*;
import com.daxt.model.service.base.result.UserInfo;
import com.daxt.model.service.use.vo.UseBorrowRecord;
import com.daxt.service.*;
import com.daxt.utils.ArchivesUtil;
import com.daxt.utils.BaseUtil;
import com.daxt.utils.IpUtil;
import com.google.common.base.Joiner;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.daxt.mapper.archives.ArchivesDocFileMapper;
import com.daxt.mapper.archives.ArchivesDocMapper;
import com.daxt.mapper.archives.ArchivesTypeDocMapper;
import com.daxt.mapper.sys.ArchivesFondsMapper;
import com.daxt.mapper.sys.ArchivesTypeMapper;
import com.daxt.model.service.archives.result.ArchivesCols;
import com.daxt.model.service.archives.result.ArchivesDetails;
import com.daxt.model.service.archives.result.ArchivesList;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import springfox.documentation.annotations.ApiIgnore;

@Api(tags = "文件整理")
@RestController
@RequestMapping("/fileManager")
public class DocController {

    @Autowired
    private ArchivesDocMapper archivesDocMapper;
    @Autowired
    private ArchivesTypeMapper archivesTypeMapper;
    @Autowired
    private ArchivesTypeDocMapper archivesTypeDocMapper;
    @Autowired
    private ArchivesFondsMapper archivesFondsMapper;
    @Autowired
    private ArchivesDocFileMapper archivesDocFileMapper;
    @Autowired
    private DocService docService;
    @Autowired
    private OperationLogService operationLogService;
    @Autowired
    private ArchivesService archivesService;
    @Autowired
    private FondsListService fondsListService;
    @Autowired
    private DicMapper dicMapper;
    @Autowired
    private ArchivesClassMapper archivesClassMapper;
    @Autowired
    private UserService userService;
    @Autowired
    private UseBorrowRecordMapper useBorrowRecordMapper;
    @Autowired
    private ArchivesBehaveLogService archivesBehaveLogService;

    @LoginAuth()
    @ApiOperation(value = "获取列表  卷/件", notes = "")
    @GetMapping("/doc")
    public Result<ArchivesList> list(@ApiParam("") @RequestParam(value = "pageNum", required = false) Integer pageNum,
                                     @ApiParam("") @RequestParam(value = "pageSize", required = false) Integer pageSize,
                                     @ApiParam("全宗ID") @RequestParam(value = "fondsId", required = false) String fondsId,
                                     @ApiParam("门类ID") @RequestParam(value = "typeId", required = false) String typeId,
                                     @ApiParam("分类ID") @RequestParam(value = "classId", required = false) String classId,
                                     @ApiParam("dossierId   0文件  dossierId卷下的件列表 ") @RequestParam(value = "dossierId", required = false) String dossierId,
                                     @ApiParam("卷dossier 件doc  scattered 散文件") @RequestParam(value = "fileType", required = false) String fileType,
                                     @ApiParam("0 整理 1归档审批 2归档 3 鉴定 4销毁 5回收站 6预归档") @RequestParam(value = "state", required = false) String state,
                                     @ApiParam("条件") @RequestParam(value = "condition", required = false) String condition,
                                     @ApiParam("条件中文") @RequestParam(value = "conditionCn", required = false) String conditionCn,
                                     @ApiParam("关键词") @RequestParam(value = "keywords", required = false) String keywords,
                                     @ApiParam("部门") @RequestParam(value = "deptId", required = false) String deptId,
                                     @ApiParam("系统来源id") @RequestParam(value = "docFrom" ,required = false) String docFrom,
                                     @ApiParam("责任者单位") @RequestParam(value = "dutyCompany" ,required = false) String dutyCompany,
                                     @ApiIgnore @LoginUser UserInfo loginUser,HttpServletRequest request) {
        System.out.println("=====================");
        //获取分类数据权限
        Classifys c = userService.buildUserClassifys(loginUser);
        List<Long> classIds = c.getClassIds();
        String idsString = idsString = Joiner.on(",").join(classIds).trim();
        ArchivesSearch as = ArchivesSearch.builder().fondsId(fondsId).typeId(typeId).classId(classId)
                .condition(condition)
                .keywords(keywords)
                .fileType(fileType)
                .deptId(deptId)
                .state(state)
                .isDelete(BaseConstants.DELETE_NORMAL)
                .dossierId(dossierId)
                .classIds(idsString)
                .docFrom(docFrom)
                .dutyCompany(dutyCompany)
                .build();

        Result<ArchivesList> list = docService.list(pageNum, pageSize, as);
        String ip= IpUtil.getIP(request);
        if (!StringUtils.isEmpty(keywords) && StringUtils.isEmpty(conditionCn))
            operationLogService.saveLog("3", "检索【" + keywords + "】", loginUser,ip);
        if (!StringUtils.isEmpty(keywords) && !StringUtils.isEmpty(conditionCn))
            operationLogService.saveLog("3", "检索【" + keywords + "】," + conditionCn + "", loginUser,ip);
        if (StringUtils.isEmpty(keywords) && !StringUtils.isEmpty(conditionCn))
            operationLogService.saveLog("3", "检索" + conditionCn + "", loginUser,ip);

        return list;
    }

    @ApiOperation(value = "放入回收站  卷/件", notes = "")
    @DeleteMapping("/doc/{fileType}")
    @Transactional(rollbackFor = Exception.class)
    @LoginAuth()
    public Result<ArchivesList> list(@ApiIgnore @LoginUser UserInfo loginUser,
                                     @ApiParam("卷dossier 件doc  scattered 散文件") @PathVariable("fileType") String fileType,
                                     @RequestBody List<String> ids,
                                     HttpServletRequest request) {
        try {

            QueryWrapper<UseBorrowRecord> queryWrapper=new QueryWrapper<>();
            queryWrapper.in("fileId",ids);
            List<UseBorrowRecord> useBorrowRecords = useBorrowRecordMapper.selectList(queryWrapper);
            if(useBorrowRecords.size()>0){
                String title= useBorrowRecords.get(0).getTitle();
                return ResultUtil.data(ResultCode.RESULT_ERROR.getCode(), "删除失败，"+title+"已被借阅", null);
            }

            ArchivesDoc entity = new ArchivesDoc();

            entity.setIsDelete("1");
            QueryWrapper<ArchivesDoc> updateWrapper = new QueryWrapper<ArchivesDoc>();
            updateWrapper.in("id", ids);
            if ("doc".equals(fileType) || "scattered".equals(fileType)) {
                archivesDocMapper.update(entity, updateWrapper);
            } else if ("dossier".equals(fileType)) {
                archivesDocMapper.update(entity, updateWrapper);
                QueryWrapper<ArchivesDoc> updateWrapperDoc = new QueryWrapper<ArchivesDoc>();
                updateWrapperDoc.in("dossierId", ids);
                archivesDocMapper.update(entity, updateWrapperDoc);
            } else {
                return ResultUtil.data(ResultCode.RESULT_ERROR.getCode(), "文件类型异常", null);
            }

            archivesBehaveLogService.saveArchivesBehaveLog(new ArchivesBehaveLog(BaseUtil.listToString(ids),BehaveLogType.DELETE.getKey(),BehaveLogType.DELETE.getValue(),"将档案放入回收站"),loginUser ,request);

            String ip= IpUtil.getIP(request);
            operationLogService.saveLog("5", "加入回收站", loginUser,ip);

            return ResultUtil.data(ResultCode.RESULT_SUCCESS.getCode(), "删除成功", null);
        } catch (Exception e) {
            e.printStackTrace();
            return ResultUtil.data(ResultCode.RESULT_ERROR.getCode(), "删除失败", null);
        }
    }


    @ApiOperation(value = "案件详情", notes = "")
    @GetMapping("/doc/{id}")
    public Result<ArchivesDetails> details(@PathVariable("id") String id) {
        ArchivesDoc archivesDoc = archivesDocMapper.selectById(id);
        if (archivesDoc == null) {
            return ResultUtil.data(ResultCode.RESULT_ERROR.getCode(), "案件信息查找不到", null);
        }

        //获取全宗号
        if(null != archivesDoc.getFondsId()){
            ArchivesFonds af = archivesFondsMapper.selectById(archivesDoc.getFondsId());
            archivesDoc.setFondsNum(af.getFondsNum());
            archivesDoc.setFondsName(af.getFondsName());
        }
        //获取分类号
        if(null != archivesDoc.getClassId()){
            ArchivesClass ac = archivesClassMapper.selectById(archivesDoc.getClassId());
            archivesDoc.setClassNum(ac.getClassNum());
            archivesDoc.setClassName(ac.getClassName());
        }

        return docService.details(archivesDoc);
    }

    @ApiOperation(value = "获取字段", notes = "")
    @GetMapping("/doc/cols")
    public Result<ArchivesCols> getCols(@ApiParam("") @RequestParam(value = "typeId", required = false) String typeId,
                                        @ApiParam("") @RequestParam(value = "fondsId", required = false) String fondsId,
                                        @RequestParam(value = "colType", required = false) String colType) {
        ArchivesCols archivesCols = new ArchivesCols();

        //获取门类
        ArchivesType typeBean = archivesTypeMapper.selectById(typeId);
        if (typeBean != null ) {
            QueryWrapper<ArchivesTypeDoc> col = new QueryWrapper<>();
            col.eq("extType", "doc");
            //col.eq("isEdit", "1");
            col.eq("typeId", typeBean.getId());
            if ("insert".equals(colType)) {
                col.eq("isInsert", "1");
            } else if ("edit".equals(colType)) {
                col.eq("isEdit", "1");
            } else if ("list".equals(colType)) {
                col.eq("isList", "1");
            } else if ("import".equals(colType)) {
                col.eq("isImport", "1");
            } else if ("export".equals(colType)) {
                col.eq("isExport", "1");
            } else if ("isBathEdit".equals(colType)) {
                col.eq("isBathEdit", "1");
            }
            List<ArchivesTypeDoc> baseCols = archivesTypeDocMapper.selectList(col);
            archivesCols.setDocBaseList(baseCols);
        }
        return ResultUtil.data(ResultCode.RESULT_SUCCESS.getCode(), "", archivesCols);
    }

    @ApiOperation(value = "保存文件", notes = "")
    @PostMapping("/doc")
    @OperLog(operModul = "添加件", operType = "ADD", operDesc = "")
    @Transactional(rollbackFor = Exception.class)
    @LoginAuth()
    public Result<String> docSave(@ApiIgnore @LoginUser UserInfo loginUser,@RequestBody ArchivesDoc archivesDoc,HttpServletRequest request) {

        if(archivesDoc.getDossierId()!=0 && archivesDoc.getDossierId()!=null){
            ArchivesDoc archivesDossier= archivesDocMapper.selectById(archivesDoc.getDossierId());
            archivesDoc.setClassId(archivesDossier.getClassId());
        }

        if (!archivesService.verifyDocNum(archivesDoc))
            return ResultUtil.data(ResultCode.RESULT_ERROR.getCode(), "件号重复：" + archivesDoc.getItemNum(), null);

        ArchivesType atBean = archivesTypeMapper.selectById(archivesDoc.getTypeId());
        if (null == atBean) return ResultUtil.error("门类不正确");
        String model = atBean.getModel();
//        if(StringUtils.isNotEmpty(archivesDoc.getClassNum())){
//            String classsYmbol = RedisUtil.getSysConfig(SystemConfigType.CLASSNUM_WEB).trim();
//            archivesDoc.setClassNum(atBean.getTypeNum() + classsYmbol + archivesDoc.getClassNum());
//        }else{
//            archivesDoc.setClassNum(atBean.getTypeNum() );
//        }

        archivesDoc.setDocFrom(DicDocFrom.FROM_1.getKey());


        boolean sole = false;//是否校验唯一性  档案号
        //0件 1卷
        if (DicDocPattern.PATTERN_0.getKey().equals(model)) {
            if (!archivesService.verifyDDoc(archivesDoc))
                return ResultUtil.data(ResultCode.RESULT_ERROR.getCode(), "存在重复件号" + archivesDoc.getItemNum(), null);
            //archivesDoc.setDossierId(1L);
            Map parseObject = JSON.parseObject(JSON.toJSONString(archivesDoc), Map.class);

            //构造档案号   lig  2021-06-09
            if(StringUtils.isNotEmpty(archivesDoc.getFondsId())){
                ArchivesFonds archivesFonds = archivesFondsMapper.selectById(archivesDoc.getFondsId());
                archivesDoc.setFondsNum(archivesFonds.getFondsNum());
            }
            Result<String> r = archivesService.buildArchivalNum(archivesDoc, atBean, sole);
            if (r.getCode().equals(ResultCode.RESULT_ERROR.getCode())) return r;


        } else {
            QueryWrapper<ArchivesDoc> queryWrapperDossierCount = new QueryWrapper<ArchivesDoc>();
            queryWrapperDossierCount.eq("id", archivesDoc.getDossierId());
            Integer dossier = archivesDocMapper.selectCount(queryWrapperDossierCount);// ById(archivesDoc.getDossierId());
            if (dossier == null || dossier.intValue() == 0) {
                return ResultUtil.data(ResultCode.RESULT_ERROR.getCode(), "案卷不存在", null);
            }
        }


//        //解析分类树
//        archivesService.parseClassNum(archivesDoc);

//        archivesService.gainClassNum


        archivesDoc.setFileType("doc");
        archivesDoc.setCreateTime(LocalDateTime.now());
        archivesDoc.setDocFrom("1");
        archivesDoc.setTypeId(atBean.getId());
        ArchivesDoc.initData(archivesDoc);
        Result<String> docSave = docService.docSave(archivesDoc);

        if(docSave.getCode().equals(ResultCode.RESULT_SUCCESS.getCode())){
            archivesBehaveLogService.saveArchivesBehaveLog(new ArchivesBehaveLog(archivesDoc.getId().toString(),BehaveLogType.ADD.getKey(),BehaveLogType.ADD.getValue(),"创建案件"),loginUser ,request);
        }

//		operationLogService.saveLog("2", "添加件："+JSON.toJSONString(archivesDoc)+"件"+(docSave.getCode().equals(ResultCode.RESULT_SUCCESS.getCode())?"成功":"失败"), request);
        return docSave;
    }

    @ApiOperation(value = "保存散文件", notes = "")
    @PostMapping("/docScattered")
    @OperLog(operModul = "添加散文件", operType = "ADD", operDesc = "新日志")
    public Result<String> docScattered(@RequestBody ArchivesDoc archivesDoc) {
        ArchivesType atBean = archivesTypeMapper.selectById(archivesDoc.getTypeId());
        if (atBean == null) return ResultUtil.error("门类不正确");

        archivesDoc.setFileType(DicDocFileType.SCATTERED.getKey());
        if (!archivesService.verifyDocNum(archivesDoc))
            return ResultUtil.data(ResultCode.RESULT_ERROR.getCode(), "件号重复：" + archivesDoc.getItemNum(), null);
        String model = atBean.getModel();
        if ("0".equals(model)) {

            archivesDoc.setDossierId(1L);
            Map parseObject = JSON.parseObject(JSON.toJSONString(archivesDoc), Map.class);
            String genArchivalNum = fondsListService.genArchivalNum(atBean.getGenArchivalNum(), atBean.getGenType(), parseObject);
            if (StringUtils.isEmpty(genArchivalNum))
                return ResultUtil.data(ResultCode.RESULT_ERROR.getCode(), "档号拼接列不能为空，请检查类目生成规则！！！", null);
            archivesDoc.setArchivalNum(genArchivalNum);
        }

//        //解析分类树
//        archivesService.parseClassNum(archivesDoc);


        archivesDoc.setDossierId(0L);

        archivesDoc.setState(StringUtils.isEmpty(archivesDoc.getState()) ? DicDocState.neaten.getKey() : archivesDoc.getState());
//		archivesDoc.setFileType("scattered");
        archivesDoc.setDocFrom("1");
        archivesDoc.setCreateTime(LocalDateTime.now());
        archivesDoc.setTypeId(atBean.getId());
        ArchivesDoc.initData(archivesDoc);
        return docService.docSave(archivesDoc);
    }

    @ApiOperation(value = "案件移动到散文件", notes = "")
    @PutMapping("/docScattered")
    @OperLog(operModul = "卷内文件移动到散文件", operType = "UPDATE", operDesc = "新日志")
    @LoginAuth()
    public Result<String> docScatteredEdit(@ApiIgnore @LoginUser UserInfo loginUser,
                                           @RequestBody List<String> docId,
                                           HttpServletRequest request) {

        //根据产品要求，增加校验件号
        for (String dId : docId) {
            ArchivesDoc adBean = archivesDocMapper.selectById(dId);
            adBean.setFileType(DicDocFileType.SCATTERED.getKey());
            adBean.setDossierId(null);
//            //校验件号是否重复，根据指定规则
//            if (!archivesService.verifyDocNum(adBean)) {
////				docId.remove(dId);
//                return ResultUtil.data(ResultCode.RESULT_ERROR.getCode(), "存在重复件号:" + adBean.getItemNum(), null);
//            }
        }

        QueryWrapper<ArchivesDoc> updateWrapper = new QueryWrapper<ArchivesDoc>();
        ArchivesDoc entity = new ArchivesDoc();

        entity.setFileType("scattered");
        updateWrapper.in("id", docId);

        int rows=archivesDocMapper.update(entity, updateWrapper);
        if(rows>0){
            archivesBehaveLogService.saveArchivesBehaveLog(new ArchivesBehaveLog(BaseUtil.listToString(docId),BehaveLogType.MOVE_SCATTERED.getKey(),BehaveLogType.MOVE_SCATTERED.getValue(),"转移到散文件中；"),loginUser ,request);
        }

        return ResultUtil.data(ResultCode.RESULT_SUCCESS.getCode(), "", null);
    }

    @ApiOperation(value = "修改", notes = "")
    @PutMapping("/doc")
//    @OperLog(operModul = "编辑件", operType = "UPDATE", operDesc = "新日志")
    @Transactional(rollbackFor = Exception.class)
    @LoginAuth()
    public Result<String> docEdit(@ApiIgnore @LoginUser UserInfo loginUser,@RequestBody ArchivesDoc archivesDoc, HttpServletRequest request, HttpServletResponse response) {

        ArchivesDoc docOld=archivesDocMapper.selectById(archivesDoc.getId());

        if (!archivesService.verifyDocNum(archivesDoc))
            return ResultUtil.data(ResultCode.RESULT_ERROR.getCode(), "件号重复：" + archivesDoc.getItemNum(), null);
        if (null != archivesDoc.getDossierId()) {
            QueryWrapper<ArchivesDoc> queryBy = new QueryWrapper<ArchivesDoc>();
            queryBy.eq("dossierId", archivesDoc.getDossierId());
            List<ArchivesDoc> selectList = archivesDocMapper.selectList(queryBy);
            if (selectList == null)
                return ResultUtil.error("案卷不存在");
        }
//        //解析分类树
//        archivesService.parseClassNum(archivesDoc);

        Result<String> result = docService.docEdit(archivesDoc);
        if (result.getCode().equals(ResultCode.RESULT_SUCCESS.getCode())) {
            if(null == archivesDoc){
                //  临时解决
                archivesDoc.setFileType(archivesDocMapper.selectById(archivesDoc.getId()).getFileType());
            }

            if (archivesDoc.getFileType().equals(DicDocFileType.DOC.getKey()))
                operationLogService.saveLog("2", "编辑件", request);
            if (archivesDoc.getFileType().equals(DicDocFileType.SCATTERED.getKey()))
                operationLogService.saveLog("2", "编辑散文件", request);

            Map<String,String> typeDocMap = archivesService.gainMetadataEditField(docOld.getTypeId(),docOld.getFileType());

            if(!typeDocMap.isEmpty()){
                String description = ArchivesUtil.compareArchives(docOld,archivesDoc,typeDocMap);
                archivesBehaveLogService.saveArchivesBehaveLog(new ArchivesBehaveLog(archivesDoc.getId().toString(),BehaveLogType.UPDATE.getKey(),BehaveLogType.UPDATE.getValue(),description),loginUser ,request);
            }

        }
        return result;
    }

    @ApiOperation(value = "删除", notes = "")
    @DeleteMapping("/doc")
    @OperLog(operModul = "删除案卷/件", operType = "DELETE", operDesc = "新日志")
    public Result<String> docDel(@RequestBody List<String> ids) {
        archivesDocMapper.deleteBatchIds(ids);
        return ResultUtil.success();
    }

    @ApiOperation(value = "案件归档审批", notes = "")
    @PostMapping("/doc/file")
    @OperLog(operModul = "案件归档审批", operType = "UPDATE", operDesc = "新日志")
    public Result<String> filing(@ApiParam("全宗ID") @RequestParam(value = "fondsId") String fondsId
            , @ApiParam("门类ID") @RequestParam(value = "typeId") String typeId
            , @ApiParam("分类Id") @RequestParam(value = "classId") String classId
            , @ApiParam("state") @RequestParam(value = "state",required = false ) String state
            ,@RequestBody List<String> ids) {

        ArchivesType at = null;
        if (org.apache.commons.lang3.StringUtils.isNotEmpty(typeId)) {
            at = archivesTypeMapper.selectById(Long.parseLong(typeId));
            if (null == at) return ResultUtil.error( "门类不正确");
        }

        if(org.springframework.util.StringUtils.isEmpty(classId)){
            QueryWrapper<ArchivesDoc> wrapper = new QueryWrapper<ArchivesDoc>();
            wrapper.select("distinct classId");
            wrapper.eq("typeId",typeId);
            wrapper.eq("fondsId",fondsId);
            wrapper.in("id",ids);
            List<ArchivesDoc> classIds= archivesDocMapper.selectList(wrapper);//获取ids下包含的classId
            Map<String,List<String>> map=new HashMap<>();
            for (int i=0;i<classIds.size();i++){
                String cId=classIds.get(i).getClassId().toString();
                wrapper = new QueryWrapper<ArchivesDoc>();
                wrapper.select("id");
                wrapper.eq("typeId",typeId);
                wrapper.eq("fondsId",fondsId);
                wrapper.eq("classId",cId);
                wrapper.in("id",ids);
                List<ArchivesDoc> docListId= archivesDocMapper.selectList(wrapper);//获取对应classId的docId集合
                List<String> listId=new ArrayList<>();
                for(int j=0;j<docListId.size();j++){
                    String id=docListId.get(j).getId().toString();
                    listId.add(id);
                }
                map.put(cId,listId);
            }
            //遍历集合对与classId对应的ids进行件号卷号的生成
            for (Map.Entry<String, List<String>> entry : map.entrySet()) {
                Result str= archivesService.automationDossierItemNumNum(at,"doc",entry.getKey(),fondsId,entry.getValue());
                if("1001".equals(str.getCode())){
                    return str;
                }
            }

        }else{
            Result str= archivesService.automationDossierItemNumNum(at,"doc",classId,fondsId,ids);
            if("1001".equals(str.getCode())){
                return str;
            }
        }


        ArchivesDoc entity = new ArchivesDoc();
        //if (StringUtils.isNotEmpty(state) && "6".equals(state)){
        //    entity.setState(DicDocState.neaten.getKey());
        //}else {
            entity.setState(DicDocState.approval.getKey());
        //}
        QueryWrapper<ArchivesDoc> updateWrapper = new QueryWrapper<ArchivesDoc>();
        updateWrapper.in("id", ids);
        archivesDocMapper.update(entity, updateWrapper);
        return ResultUtil.data(ResultCode.RESULT_SUCCESS.getCode(), null, null);
    }


    @ApiOperation(value = "自动组卷(根据导入散文件的类目号、全宗号、门类号、案卷号进行自动组卷，请先确认卷目录是否导入)", notes = "")
    @PostMapping("/doc/autoDossier/{fondsId}/{typeId}/{state}")
    @Transactional(rollbackFor = Exception.class)
    @OperLog(operModul = "自动组卷", operType = "ADD", operDesc = "新日志")
    public Result<String> setDocNum(@PathVariable("fondsId") String fondsId,
                                    @PathVariable("typeId") String typeId ,
                                    @PathVariable("state") String state) {

        ArchivesType at = archivesTypeMapper.selectById(typeId);
        if(null == at) return ResultUtil.error("门类异常");

        //匹配规则
        if (StringUtils.isEmpty(at.getConstituteRule()) || StringUtils.isEmpty(at.getConstituteRuleSymbol())) {
            return ResultUtil.data(ResultCode.RESULT_ERROR.getCode(), "组卷规则未配置，档案管理 - 全宗管理 - 档案门类配置", null);
        }

        /*QueryWrapper<ArchivesDoc> queryWrapperScattered = ArchivesUtil.builBaseQueryWrapper(new BaseQueryDto(fondsId, typeId));
        queryWrapperScattered.eq(BaseConstants.field_state, state);
        queryWrapperScattered.eq("fileType", DicDocFileType.SCATTERED.getKey());
        queryWrapperScattered.eq(BaseConstants.field_isDelete, BaseConstants.DELETE_NORMAL);
        List<ArchivesDoc> scatteredList = archivesDocMapper.selectList(queryWrapperScattered);*/

        List<ArchivesDoc> scatteredList=archivesDocMapper.queryListNoPage(fondsId,typeId,null,DicDocFileType.SCATTERED.getKey(),state);


        /*QueryWrapper<ArchivesDoc> queryWrapperDossier = ArchivesUtil.builBaseQueryWrapper(new BaseQueryDto(fondsId, typeId));
        queryWrapperDossier.eq(BaseConstants.field_state, state);
        queryWrapperDossier.eq("fileType", DicDocFileType.DOSSIER.getKey());
        queryWrapperDossier.eq(BaseConstants.field_isDelete, BaseConstants.DELETE_NORMAL);
        List<ArchivesDoc> dossierList = archivesDocMapper.selectList(queryWrapperDossier);*/

        List<ArchivesDoc> dossierList = archivesDocMapper.queryListNoPage(fondsId,typeId,null,DicDocFileType.DOSSIER.getKey(),state);

        List<ArchivesDoc> addList = new ArrayList<ArchivesDoc>();
        int errorNum = 0;

        if (scatteredList != null && scatteredList.size() > 0 && dossierList != null && scatteredList.size() > 0) {
            try {
                Set<String> hashSet = new HashSet<String>();

                scatteredList.forEach((ArchivesDoc archivesDocTemp) -> {
                    scatteredFor:
                    for (ArchivesDoc archivesDoc : dossierList) {
                        archivesDocTemp.setFileType(DicDocFileType.DOC.getKey());//校验 件类型

//                        if(!archivesService.verifyDocNum(archivesDocTemp))break scatteredFor;
                        if (!archivesService.verifyDDDoc(archivesDocTemp)) break scatteredFor;

                        if (archivesService.matchingConstitute(archivesDoc, archivesDocTemp, at)) {
                            ArchivesDoc archivesDocNew = new ArchivesDoc();
                            archivesDocNew.setId(archivesDocTemp.getId());
                            archivesDocNew.setDossierId(archivesDoc.getId());
                            archivesDocNew.setFileType(DicDocFileType.DOC.getKey());
                            archivesDocNew.setFondsName(archivesDocTemp.getFondsName());
                            archivesDocNew.setFondsId(archivesDocTemp.getFondsId());
                            archivesDocNew.setArchivalNum(archivesDocTemp.getArchivalNum());
                            archivesDocNew.setCategoryNum(archivesDocTemp.getCategoryNum());
                            archivesDocNew.setDeptId(archivesDocTemp.getDeptId());
                            archivesDocNew.setClassNum(archivesDocTemp.getClassNum());

                            addList.add(archivesDocNew);
                            break scatteredFor;
                        }

                    }
                });


            } catch (Exception e) {
                e.printStackTrace();
                e.getStackTrace();
                return ResultUtil.data(ResultCode.RESULT_ERROR.getCode(), "信息异常，请检测！！！", null);
            }
        }
        if (addList.size() > 0) {
            docService.updateBatchById(addList);
//			return ResultUtil.data(ResultCode.RESULT_SUCCESS.getCode(),"操作成功，失败条数："+ errorNum,null);
            errorNum = scatteredList.size() - addList.size();



            if (errorNum > 0)
                return ResultUtil.success( "组卷成功" + addList.size() + "条，失败" + errorNum + "条");
            return ResultUtil.success( "组卷成功" + addList.size() + "条");
        } else {
            return ResultUtil.success( "组卷失败，共" + scatteredList.size() + "条");
        }
    }


    @ApiOperation(value = "组合(组件)", notes = "")
    @PostMapping("/doc/group/{fileType}/{docId}")
    @Transactional(rollbackFor = Exception.class)
    public Result<List<String>> groupDoc(@PathVariable("fileType") String fileType,
                                         @PathVariable("docId") String docId,
                                         @RequestBody List<String> ids) {
        int i=0;
        if("doc".equals(fileType)){  //案件组件
            QueryWrapper<ArchivesDocFile> updateWrapper = new QueryWrapper<ArchivesDocFile>();
            updateWrapper.in("docId", ids);
            ArchivesDocFile adf = new ArchivesDocFile();
            adf.setDocId(Long.parseLong(docId));
            archivesDocFileMapper.update(adf, updateWrapper);
            i = archivesDocMapper.deleteBatchIds(ids);
        }else if ("scattered".equals(fileType)){//散文件组卷
            QueryWrapper<ArchivesDoc> updateWrapper = new QueryWrapper<ArchivesDoc>();
            updateWrapper.in("id", ids);
            ArchivesDoc doc=new ArchivesDoc();
            doc.setDossierId(Long.parseLong(docId));
            doc.setFileType("doc");
            doc.setItemNum("");
            i=archivesDocMapper.update(doc,updateWrapper);

            ArchivesDoc dossier=new ArchivesDoc();
            dossier.setFileType("dossier");
            dossier.setId(Long.parseLong(docId));
            archivesDocMapper.updateById(dossier);
        }else if ("dossier".equals(fileType)){//既有散文件又有案卷组卷
            QueryWrapper<ArchivesDoc> selectWrapper=new QueryWrapper<>();
            selectWrapper.eq("fileType","dossier");
            selectWrapper.eq("dossierId","0");
            selectWrapper.in("id",ids);
            List<ArchivesDoc> dossierList=archivesDocMapper.selectList(selectWrapper);

            List<Long> dossierIds=new ArrayList<>();
            if(dossierList.size()>0){
                for (ArchivesDoc doc : dossierList) {
                    dossierIds.add(doc.getId());//获取所有的案卷id
                }
                ids.remove(dossierIds);//把ids里的案卷id排除，只留散文件id
                selectWrapper=new QueryWrapper<>();
                selectWrapper.in("dossierId",dossierIds);
                List<ArchivesDoc> docList=archivesDocMapper.selectList(selectWrapper);
                List<String> docIds=new ArrayList<>();
                for (ArchivesDoc doc : docList) {
                    docIds.add(doc.getId().toString());//获取所有的案卷下案件的id
                }
                //将所有的案件id添加到ids集合中
                ids.addAll(docIds);
            }

            //获取案卷的信息，并让案件的信息与案卷信息保持一致
            ArchivesDoc dossier = archivesDocMapper.selectById(docId);


            //将所有案件的dossierId的值设为案卷id
            QueryWrapper<ArchivesDoc> updateWrapper = new QueryWrapper<ArchivesDoc>();
            updateWrapper.in("id", ids);

            ArchivesDoc doc = new ArchivesDoc();
            doc.setDossierId(Long.parseLong(docId));
            doc.setFileType("doc");
            doc.setItemNum("");
            doc.setDossierNum(dossier.getDossierNum());
            doc.setArchivalNum(dossier.getArchivalNum());
            doc.setStoragePeriod(dossier.getStoragePeriod());
            doc.setCategoryNum(dossier.getCategoryNum());
            doc.setFondsId(dossier.getFondsId());
            i=archivesDocMapper.update(doc,updateWrapper);
            //删除被组合案卷的主数据
            if(dossierList.size()>0){
                archivesDocMapper.deleteBatchIds(dossierIds);
            }

        }
        return ResultUtil.result(i);
    }


    @ApiOperation(value = "加入搜集整编", notes = "")
    @PostMapping("/doc/{fondsId}/{typeId}")
    @Transactional(rollbackFor = Exception.class)
    public Result<String> inGather(@ApiParam("全宗ID") @PathVariable("fondsId") String fondsId
            , @ApiParam("门类Id") @PathVariable("typeId") String typeId
            , @RequestBody List<String> ids) {

        ArchivesDoc entity = new ArchivesDoc();
        entity.setState("0");
        QueryWrapper<ArchivesDoc> updateWrapper = new QueryWrapper<ArchivesDoc>();
        updateWrapper.eq("fondsId", fondsId);
        updateWrapper.eq("typeId", typeId);
        updateWrapper.in("id", ids);

        return ResultUtil.result(archivesDocMapper.update(entity, updateWrapper));

    }

    @ApiOperation(value = "批量修改 件号（动态档号）", notes = "")
    @PutMapping("/batchEditDocNum/{number}")
    @Transactional(rollbackFor = Exception.class)
    public Result<String> batchEditDocNum(@ApiParam("起始编号") @PathVariable("number") String number
                                        , @RequestBody List<String> ids) {

        int num = 0;
        try {
            num = Integer.parseInt(number);
        } catch (Exception e) {
            ResultUtil.error("起始编号必须为整型");
        }
        ArchivesType atBean = null;

        for (String id : ids) {
            ArchivesDoc doc = archivesDocMapper.selectById(id);


            String numAll = num+"";
            while (numAll.length() < number.length()){
                numAll = "0" + numAll;
            }
            doc.setItemNum(numAll);
            if (!archivesService.verifyDocNumNew(doc,ids))
                return ResultUtil.error( "件号重复：" + doc.getItemNum());

            if (atBean == null) {
                atBean = archivesTypeMapper.selectById(doc.getTypeId());
                if (null == atBean) return ResultUtil.error( "门类不正确");
            }
            if(doc.getClassId()!=null&&!"".equals(doc.getClassId())){
                ArchivesClass aClass=archivesClassMapper.selectById(doc.getClassId());
                String classNum=atBean.getTypeNum()+"·"+aClass.getTreeStr();
                doc.setClassNum(classNum);
            }
            if(StringUtils.isNotEmpty(doc.getFondsId())){
                ArchivesFonds archivesFonds = archivesFondsMapper.selectById(doc.getFondsId());
                doc.setFondsNum(archivesFonds.getFondsNum());
            }
            //构造档案号
            Result<String> r = archivesService.buildArchivalNum(doc, atBean, false);
            if (r.getCode().equals(ResultCode.RESULT_ERROR.getCode())) return r;

            archivesDocMapper.updateById(doc);


            num++;
        }


        return ResultUtil.success();
    }



    @ApiOperation(value = "附件数量", notes = "")
    @GetMapping("/doc/accessory/{docId}")
    public Result<String> accessoryByDocId(@ApiParam("档案ID") @PathVariable("docId") String docId) {

        ArchivesDoc doc = archivesDocMapper.selectById(docId);
        int i = 0;
        if(doc.getFileType().equals(DicDocFileType.DOSSIER.getKey())){
            List<ArchivesDoc> docList = archivesService.gainDocById(docId);
            if(BaseUtil.listIsNotNullElement(docList)){
                List<Long> ids = new ArrayList();
                docList.forEach((ArchivesDoc ad)->{
                    ids.add(ad.getId());
                });
                i = archivesDocFileMapper.selectCount(new QueryWrapper<ArchivesDocFile>().in("docId",ids));
            }

        }else{
            i = archivesDocFileMapper.selectCount(new QueryWrapper<ArchivesDocFile>().eq("docId",doc.getId()));
        }

        return ResultUtil.success(i+"");

    }

    @ApiOperation(value = "批量修改 卷号（动态档号）", notes = "")
    @PutMapping("/batchEditDossierNum/{number}")
    @Transactional(rollbackFor = Exception.class)
    public Result<String> batchEditDossierNum(@ApiParam("起始编号") @PathVariable("number") String number,
                                              @RequestParam(value = "numberDoc",required = false) String numberDoc
                                              ,@RequestBody List<String> ids) {

        int num = 0;
        try {
            num = Integer.parseInt(number);
        } catch (Exception e) {
            ResultUtil.error("起始编号必须为整型");
        }
        ArchivesType atBean = null;

        for (String id : ids) {
            ArchivesDoc doc = archivesDocMapper.selectById(id);


            String numAll = num+"";
            while (numAll.length() < number.length()){
                numAll = "0" + numAll;
            }

            doc.setDossierNum(numAll);

            if (!archivesService.verifyDossierNumNew(doc,ids))
                return ResultUtil.error( "卷号重复：" + doc.getDossierNum());

            if (atBean == null) {
                atBean = archivesTypeMapper.selectById(doc.getTypeId());
                if (null == atBean) return ResultUtil.error( "门类不正确");
            }
            if(doc.getClassId()!=null&&!"".equals(doc.getClassId())){
                ArchivesClass aClass=archivesClassMapper.selectById(doc.getClassId());
                String classNum=atBean.getTypeNum()+"·"+aClass.getTreeStr();
                doc.setClassNum(classNum);
            }
            if(StringUtils.isNotEmpty(doc.getFondsId())){
                ArchivesFonds archivesFonds = archivesFondsMapper.selectById(doc.getFondsId());
                doc.setFondsNum(archivesFonds.getFondsNum());
            }
            //构造档案号
            //System.out.println("类目号:"+doc.getClassNum());
            Result<String> r = archivesService.buildArchivalNum(doc, atBean, false);
            if (r.getCode().equals(ResultCode.RESULT_ERROR.getCode())) return r;

            //修改卷内文件的件号
            QueryWrapper<ArchivesDoc> queryWrapper=new QueryWrapper<>();
            queryWrapper.eq("dossierId",doc.getId());
            List<ArchivesDoc> archivesDocList=archivesDocMapper.selectList(queryWrapper);
            if(numberDoc!=null){
                int numdoc=0;
                try {
                    numdoc = Integer.parseInt(numberDoc);
                } catch (Exception e) {
                    ResultUtil.error("起始编号必须为整型");
                }
                for(ArchivesDoc aDoc:archivesDocList){
                    String numA = numdoc+"";
                    while (numA.length() < numberDoc.length()){
                        numA = "0" + numA;
                    }
                    aDoc.setItemNum(numA);
                    if (!archivesService.verifyDocNum(aDoc))
                        return ResultUtil.error( "卷内文件：件号重复：" + aDoc.getItemNum());
                    archivesDocMapper.updateById(aDoc);
                    numdoc++;
                }
            }

            archivesDocMapper.updateById(doc);
            num++;
        }


        return ResultUtil.success();
    }

}
